package com.example.school.exception;

import com.example.school.utils.JsonResult;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
//ExceptionHandler的处理顺序是由异常匹配度来决定的，且我们也无法通过其他途径指定顺序(其实也没有必要)

/**
 * 全局异常处理器
 */
@ControllerAdvice // @ControllerAdvice将当前类标识为异常处理的组件
@RestController
public class GlobalExceptionHandler {
    @ExceptionHandler(DuplicateKeyException.class)
    @ResponseStatus(HttpStatus.OK)
    public JsonResult handleException(HttpServletRequest req, DuplicateKeyException ex) {
        JsonResult result = new JsonResult();
        result.setCode(1);
        result.setMsg("数据库已经存在");
        return result;
    }

    @ExceptionHandler(MaxUploadSizeExceededException.class)
    @ResponseBody
    public JsonResult handleException(HttpServletRequest req,MaxUploadSizeExceededException ex) {
        ex.printStackTrace();
        JsonResult result = new JsonResult();
        result.setCode(1);
        result.setMsg("文件过大");
        return result;
    }

    @ExceptionHandler(Exception.class)  // @ExceptionHandler用于设置所标识方法处理的异常 参数代表异常类型
    @ResponseStatus(HttpStatus.OK)
    public JsonResult handleException(HttpServletRequest req, Exception ex) {
        ex.printStackTrace();
        JsonResult result = new JsonResult();
        result.setCode(1);
        result.setMsg("系统错误");
        return result;
    }
}
